package export;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.jplus.core.db.JdbcTemplate;
import com.jplus.core.utill.SimpleSql;
import com.jplus.core.utill.StreamUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SaasExport {
	static Logger log = LoggerFactory.getLogger(SaasExport.class);
	Properties prop = new Properties();
	JdbcTemplate saas;
	JdbcTemplate lock;
	SimpleSql sql;

	public static void main(String[] args) throws ClassNotFoundException, IOException {
		SaasExport st = new SaasExport();
		st.init();
		st.exportSaasDoorlock();
	}

	/**
	 * 导出联寓协议v1.0门锁表信息
	 */
	void exportSaasDoorlock() throws ClassNotFoundException, IOException {
		List<Map<String, Object>> listRoom = saas.queryList(sql.get("listRoom"));
		log.info("房间：" + listRoom.size());
		List<Map<String, Object>> listPower = lock.queryList(sql.get("listPower"));
		log.info("门锁：" + listPower.size());
		List<Map<String, Object>> listTime = lock.queryList(sql.get("listTime"));
		log.info("时间：" + listTime.size());

		StringBuilder sb = new StringBuilder(1024);
		sb.append("派出所,警区,小区名称,详细地址,楼栋, 楼层,房间号,MAC,门锁品牌,门锁状态,安装时间,门锁电量(%),时间差值(分钟),最后上报时间\r\n");

		Map<Object, Object[]> pmap = new HashMap<>();
		for (Map<String, Object> map : listPower)
			pmap.put(map.get("lockMac"), new Object[] { map.get("lockSoc"), map.get("gmtUpdate") });
		Map<Object, Object[]> tmap = new HashMap<>();
		for (Map<String, Object> map : listTime)
			tmap.put(map.get("lockMac"), new Object[] { map.get("xTime"), map.get("gmtCreate") });

		for (Map<String, Object> map : listRoom) {
			String mac = (String) map.get("MAC");
			Object[] power = pmap.get(mac);
			if (power == null)
				power = new Object[] { 0, "" };
			Object[] xtime = tmap.get(mac);
			if (xtime == null)
				xtime = new Object[] { 0, "" };
			sb.append(map.get("派出所") + "," + map.get("警区") + "," + map.get("小区名称") + "," + map.get("详细地址") + ","
					+ map.get("楼栋") + "," + map.get("楼层") + "," + map.get("房间号") + "," + map.get("MAC") + ","
					+ map.get("门锁品牌") + "," + map.get("门锁状态") + "," + map.get("安装时间") + "," + power[0] + "," + xtime[0]
					+ "," + xtime[1] + " \r\n");

		}
		String content = sb.toString();
		StreamUtil.toWriteFile(new File("D://金钥匙门锁信息.csv"), content.getBytes("GBK"));
		log.info(">> 导出完成");
	}

	void init() throws IOException, ClassNotFoundException {
		prop.load(new FileInputStream(new File("D:/config/LY_PRD_JDBC.properties")));
		saas = new JdbcTemplate(GET(prop, "saas.jdbcurl"), GET(prop, "saas.user"), GET(prop, "saas.pass"));
		lock = new JdbcTemplate(GET(prop, "lock.jdbcurl"), GET(prop, "lock.user"), GET(prop, "lock.pass"));
		sql = new SimpleSql("simple.sql");
	}

	String GET(Properties prop, String key) {
		return prop.getProperty(key);
	}
}
